package com.example.chengzhengwei;

import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.util.Log;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;

import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;

import com.example.chengzhengwei.utils.HexUtils;
import com.example.chengzhengwei.utils.SpectrophotometerProtocol;

import java.io.IOException;

public class SelfCheckActivity extends AppCompatActivity {

    private static final String TAG = "SelfCheckActivity";
    private EditText editTextSelfCheckResult, editTextReturnCode;
    private ProgressBar progressBar;
    private TextView loadingText;
    private Handler handler = new Handler();
    private AlertDialog loadingDialog;
    private SerialApp serialApp;

    // 添加回调实例
    private SerialApp.SerialReadCallback mSelfCheckReadCallback;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_self_check);

        serialApp = (SerialApp) getApplication();

        editTextSelfCheckResult = findViewById(R.id.editTextSelfCheckResult);
        editTextReturnCode = findViewById(R.id.editTextReturnCode);

        Button buttonStart = findViewById(R.id.buttonStart);
        Button buttonBack = findViewById(R.id.buttonBack);

        progressBar = new ProgressBar(this);
        loadingText = new TextView(this);
        loadingText.setText("正在等待自检结果...");

        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setTitle("自检中");
        builder.setMessage("正在与设备通信，请稍候...");
        builder.setCancelable(false);
        loadingDialog = builder.create();

        buttonStart.setOnClickListener(v -> {
            // 清除之前的结果
            editTextSelfCheckResult.setText("");
            editTextReturnCode.setText("");

            // 显示加载对话框
            loadingDialog.show();

            // 注册接收消息回调
            registerReadingCallback();
            
            // 发送自检命令
            sendSelfCheckCommand();
        });

        buttonBack.setOnClickListener(v -> {
            finish();
        });
    }

    private void sendSelfCheckCommand() {
        // 构建自检命令
        byte[] command = SpectrophotometerProtocol.buildSelfCheckCommand(
                SpectrophotometerProtocol.PC_ADDRESS
        );

        // 通过串口发送命令
        serialApp.safeWrite(command, new SerialApp.SerialWriteCallback() {
            @Override
            public void onWriteComplete(int bytesWritten) {
                // 发送成功，等待响应
            }

            @Override
            public void onWriteError(Exception e) {
                runOnUiThread(() -> {
                    loadingDialog.dismiss();
                    unregisterReadingCallback(); // 取消注册回调
                    Toast.makeText(SelfCheckActivity.this,
                            "发送自检命令失败: " + e.getMessage(),
                            Toast.LENGTH_LONG).show();
                });
            }
        });
    }

    private void handleSelfCheckResponse(byte[] data) {
        try {
            SpectrophotometerProtocol.Response response = SpectrophotometerProtocol.parseResponse(data);

            runOnUiThread(() -> {
                loadingDialog.dismiss();
                unregisterReadingCallback(); // 处理完响应后取消注册回调

                if(response.getData()==null){
                    return;
                }
                // 检查是否是自检响应
                if (response.getCommand() == SpectrophotometerProtocol.RESP_SELF_CHECK) {
                    if (response.isSelfCheckSuccessful()) {
                        editTextSelfCheckResult.setText("自检通过");
                        editTextReturnCode.setText("0x00");

                    } else {
                        editTextSelfCheckResult.setText("自检失败");

                        // 如果有返回码数据，显示第一个字节的十六进制形式
                        if (response.getData() != null && response.getData().length > 0) {
                            byte returnCode = response.getData()[0];
                            editTextReturnCode.setText(String.format("0x%02X", returnCode));
                        } else {
                            editTextReturnCode.setText("0x01"); // 默认错误码
                        }
                    }

                } else {
                    // 非自检响应
                    editTextSelfCheckResult.setText("收到非自检响应");
                    editTextReturnCode.setText(String.format("0x%02X", response.getCommand()));
                    Toast.makeText(SelfCheckActivity.this,
                            "收到非预期响应: " + String.format("0x%02X", response.getCommand()),
                            Toast.LENGTH_LONG).show();
                }
            });

        } catch (SpectrophotometerProtocol.ProtocolException e) {
            runOnUiThread(() -> {
                loadingDialog.dismiss();
                unregisterReadingCallback(); // 取消注册回调
                Toast.makeText(SelfCheckActivity.this,
                        "协议解析错误: " + e.getMessage(),
                        Toast.LENGTH_LONG).show();
                editTextSelfCheckResult.setText("解析错误");
                editTextReturnCode.setText("N/A");
            });
        }
    }

    @Override
    protected void onResume() {
        super.onResume();
        // 不再在onResume中自动注册读取
    }

    @Override
    protected void onPause() {
        super.onPause();
        // 确保在离开界面时停止读取
        unregisterReadingCallback();
    }

    @Override
    protected void onStop() {
        super.onStop();
        // 确保在停止时取消回调
        unregisterReadingCallback();
    }

    private void unregisterReadingCallback() {
        // 停止读取并清空回调
        serialApp.stopReading();
        mSelfCheckReadCallback = null;
    }

    private void registerReadingCallback() {
        if (mSelfCheckReadCallback == null) {
            // 创建回调
            mSelfCheckReadCallback = new SerialApp.SerialReadCallback() {
                @Override
                public void onDataReceived(byte[] data) {
                    handleSelfCheckResponse(data);
                }

                @Override
                public void onReadError(Exception e) {
                    runOnUiThread(() -> {
                        loadingDialog.dismiss();
                        Toast.makeText(SelfCheckActivity.this,
                                "读取自检响应失败: " + e.getMessage(),
                                Toast.LENGTH_LONG).show();
                        // 出错时也取消回调
                        unregisterReadingCallback();
                    });
                }
            };
        }
        
        // 开始接收数据
        serialApp.startReading(mSelfCheckReadCallback);
    }
}